import React, { useState, useEffect } from 'react';
// import styles from '../styles/Reference.module.css';
import '../styles/Reference.module.css';

import { List, Typography, Modal, Tooltip, Collapse, Drawer, Card, message } from 'antd';
import { FileOutlined } from '@ant-design/icons';
import { SvgIcon } from '@/components/icon';

import { Quote } from '../tools/constants';
import useWindowWidth from '@/hooks/event/use-window-width';
import datasetService from '@/api/services/datasetService';
import '../styles/reference.css';
import FilePreviewDrawer from '@/pages/components/fileviewer/FilePreviewDrawer';

import { useDatasetPermit } from '@/store/configStore';

const { Text } = Typography;
const { Panel } = Collapse;

const Reference: React.FC<{ files: Quote[]; onChange: (isExpanded: boolean) => void }> = ({
  files,
  onChange,
}) => {
  const [groupedFiles, setGroupedFiles] = useState<{ [key: string]: Quote[] }>({});
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [referenceDetail, setReferenceDetail] = useState<Quote[]>([]);
  const [isPanelExpanded, setIsPanelExpanded] = useState(false);
  const { isPc } = useWindowWidth();
  const [isPreview, setIsPreview] = useState(false);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const [previewFileName, setPreviewFileName] = useState<string>('');
  const [loading, setLoading] = useState(false);

  const datasetPermit = useDatasetPermit();

  useEffect(() => {
    const grouped = files.reduce((acc, file) => {
      const key = file?.sourceName;
      if (!acc[key]) {
        acc[key] = [];
      }
      const scoreItem = file?.score.find((item) => item.type === 'fullText');
      if (scoreItem) {
        file.s = scoreItem.value;
      }
      acc[key].push(file);
      return acc;
    }, {} as { [key: string]: Quote[] });

    for (const sourceName in grouped) {
      grouped[sourceName].sort((a, b) => {
        // const scoreA = a.score.find(s => s.type === 'fullText')?.value || 0;
        // const scoreB = b.score.find(s => s.type === 'fullText')?.value || 0;
        // return scoreB - scoreA;
        return b.s - a.s;
      });
    }

    setGroupedFiles(grouped);
  }, [files]);

  const referenceStyle: React.CSSProperties = {
    borderRadius: '4px',
  };

  // const uniqueFiles = Array.from(new Set(files.map((file) => file?.sourceName)))
  //   .map((sourceName) => files.find((file) => file?.sourceName === sourceName))
  //   .filter(Boolean) as Quote[];

  const uniqueFiles = Array.from(new Set(files.map((file) => file?.sourceName)))
    .map((sourceName) => files.find((file) => file?.sourceName === sourceName))
    .filter(Boolean)
    .filter((file) => file?.datasetId && datasetPermit.includes(file?.datasetId)) as Quote[];

  const processText = (inputText: string) => {
    // 使用正则表达式去除 HTML 标签
    const textWithoutHtml = inputText
      .replace(/<[^>]*>/g, '\n')
      .replace(' ', '\n')
      .replace(/[^a-zA-Z\u4e00-\u9fa5\s]/g, '\n');
    // 按行分割文本，去除空行，然后用竖线连接
    const lines = textWithoutHtml
      .split('\n')
      .map((line) => line.trim()) // 去掉每行的首尾空格
      .filter((line) => line !== ''); // 去除空行
    const result = lines.join('|');
    return result;
  };
  const showDrawer = async (source: Quote) => {
    setReferenceDetail(groupedFiles[source.sourceName] || []);

    try {
      const res = await datasetService.collectionPreviewInfo({
        collection_id: source.collectionId,
      });
      if (res && res.url) {
        if (!res.preview) {
          message.error('文件不支持预览！');
          return;
        }
        setLoading(true);
        var keyword = res.show_keyword ? processText(source.q) : '';
        if (keyword.length > 200) {
          keyword = keyword.substring(0, 200);
        }
        if (res.type == 'file') {
          setPreviewFileName(res.filename);
          if (res.filename.endsWith('.md')) {
            setPreviewUrl(res.file_url);
          } else {
            setPreviewUrl(res.url + `&officePreviewType=pdf&keyword=${keyword}`);
          }
          setIsPreview(true);
        } else {
          window.open(res.url);
        }
      }
    } catch (error) {
      console.log(error);
      message.error(error.message);
    }
  };

  const onCloseDrawer = () => {
    setIsDrawerOpen(false);
  };

  const onClosePreview = () => {
    setIsPreview(false);
  };

  const handleCollapseChange = (key: string | string[]) => {
    const isExpanded = key.length > 0;
    setIsPanelExpanded(isExpanded);
    onChange(isExpanded);
  };

  return (
    <>
      {uniqueFiles.length > 0 && (
        <div style={referenceStyle} className="custom-reference">
          <Collapse className="custom-collapse" accordion onChange={handleCollapseChange}>
            <Panel
              header={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <SvgIcon icon="ic_rj_reference" size="10" />
                  <span
                    style={{
                      color: '#8E93A4',
                      paddingLeft: '10px',
                      paddingRight: '10px',
                      fontSize: '12px',
                    }}
                  >{`引用 ${uniqueFiles.length} 份资料回答`}</span>
                  {isPanelExpanded ? (
                    <SvgIcon icon="ic_rj_up" size="10" />
                  ) : (
                    <SvgIcon icon="ic_rj_down" size="10" />
                  )}
                </div>
              }
              key="1"
              className="custom-panel"
            >
              <div
                style={{
                  // display: 'flex',
                  flexWrap: 'wrap',
                  gap: '16px',
                  // padding: '10px 0',
                }}
              >
                {uniqueFiles.map((item) => (
                  <div
                    key={item.id}
                    onClick={() => showDrawer(item)}
                    style={{
                      borderRadius: '5px',
                      padding: '2px 5px',
                      borderColor: '#E8EBF0',
                      cursor: 'pointer',
                      maxWidth: '100%',
                    }}
                  >
                    <div className="file-name">
                      <FileOutlined
                        className="icon"
                        style={{ fontSize: '16px', color: '#985ae1' }}
                      />{' '}
                      <span className="ellipsis">{item?.sourceName}</span>
                    </div>
                  </div>
                ))}
              </div>
            </Panel>
          </Collapse>
        </div>
      )}

      <Drawer
        title={referenceDetail.length > 0 ? referenceDetail[0].sourceName : ''}
        placement="right"
        onClose={onCloseDrawer}
        open={isDrawerOpen}
        zIndex={500}
        width={isPc ? '30%' : '100%'}
        closeIcon={isPc ? undefined : <SvgIcon icon="ic-back" size={24} />}
      >
        {referenceDetail.map((item, index) => (
          <Card key={index} style={{ marginBottom: '16px' }} title={`综合得分: ${item.s}`}>
            <p style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }}>{item.q}</p>
          </Card>
        ))}
      </Drawer>
      <FilePreviewDrawer
        loading={loading}
        setLoading={setLoading}
        open={isPreview}
        previewUrl={previewUrl}
        fileName={previewFileName}
        onClose={onClosePreview}
      />
    </>
  );
};

export default Reference;
